﻿using System;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net;
using System.Drawing.Drawing2D;
using System.Web;
namespace ART.Common
{
    /// <summary>
    /// 上传操作类
    /// Create by Jinlong Zhang
    /// </summary>
    public class JUpload
    {

        #region __________属性__________


        private int _filesize = 200;
        /// <summary>
        /// 允许上传文件大小,单位为KB
        /// </summary>
        public int FileSize
        {
            get { return _filesize; }
            set { _filesize = value; }
        }


        private string _filetype = "image";
        /// <summary>
        /// 允许上传文件格式 可选all,office,image,flash,media,xml,pdf,fj默认为image
        /// </summary>
        public string FileType
        {
            get { return _filetype; }
            set { _filetype = value; }
        }


        private bool _iswatermark = false;
        /// <summary>
        /// 是否添加水印 true 添加，false,不添加,默认为false
        /// </summary>
        public bool IsWaterMark
        {
            get { return _iswatermark; }
            set { _iswatermark = value; }
        }

        private bool _ischangename = true;
        /// <summary>
        /// 是否自动改名字
        /// </summary>
        public bool IsChangeName
        {
            get { return _ischangename; }
            set { _ischangename = value; }
        }


        private bool _isusedftp = false;
        /// <summary>
        /// 是否远程
        /// </summary>
        public bool IsUsedFtp
        {
            get { return _isusedftp; }
            set { _isusedftp = value; }
        }


        private string _strwatermarkpath = "/img/watermark.png";
        /// <summary>
        /// 水印图片地址
        /// </summary>
        public string strWaterMarkPath
        {
            get { return _strwatermarkpath; }
            set { _strwatermarkpath = value; }
        }




        #endregion



        /// <summary>
        /// 上传文件并返回文件名或错误信息(0:文件格式不正确,1,文件大小超过设置的范围，默认为200K，)
        /// </summary>
        /// <param name="file">FileUpload控件名</param>
        /// <param name="filepath">相对路径.如:/web/upload/"</param>
        /// <returns>返回上传后文件全路径</returns>
        public string SaveFile(FileUpload file, string filepath)
        {

            string strOldFilePath = file.PostedFile.FileName; //待上传的文件路径

            string strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf(".")).ToLower();//待上传文件的扩展名

            string strNewFileName = GetUniqueString() + strExtension;//按当前时间生成新的文件名

            if (!_ischangename) //如果不改名
            {
                strNewFileName = strOldFilePath.Substring(strOldFilePath.LastIndexOf("\\")+1).ToLower();
            }

            
            string fileType = file.PostedFile.ContentType;//待上传文件类型

 

            filepath = filepath + GetFoderString() + "/";//按当前日期生成新的文件上传路径

            //如果待上传文件的文件名不为空
            if (strOldFilePath != string.Empty)
            {
                if (fileType=="image")
                {
                    if (!isPic(file, null))
                {
                    return "3";
                }
                }
                
                //验证文件格式
                if (!IsAllowedExtension(strOldFilePath))
                {
                    return "0";
                }
                //验证文件大小
                if (!IsAllowedLength(file.PostedFile.ContentLength))
                {
                    return "1";
                }


                //加水印后的图片的文件名
                string strNewFileName_Mark = GetUniqueString() + "_Mark" + strExtension;

                //水印图片绝对路径
                string strWaterMarkPath = System.Web.HttpContext.Current.Server.MapPath(_strwatermarkpath);

                string strNewFilePathAndName_Mark = "";
                string strAbsolutePath = string.Empty;//要上传文件的绝对路径
                if (!IsUsedFtp)
                {
                    strAbsolutePath = System.Web.HttpContext.Current.Server.MapPath(filepath);

                }
                else //如果启用FTP，则先上传到本地的temp文件夹下
                {
                    strAbsolutePath = System.Web.HttpContext.Current.Server.MapPath("/temp/");
                }
                #region __________本地上传__________




                string strNewFilePathAndName = strAbsolutePath + strNewFileName; //文件上传后的路径+文件名


                strNewFilePathAndName_Mark = strAbsolutePath + strNewFileName_Mark;//加水印图片后的路径+文件名

                //如果文件夹不存在 则创建

                if (!Directory.Exists(Path.GetDirectoryName(strAbsolutePath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(strAbsolutePath));
                }

                //上传
                file.PostedFile.SaveAs(strNewFilePathAndName);
                file.Dispose();
                //添加水印
                if (_iswatermark == true)
                {
                    #region ___水印___
                    if ((strExtension == ".bmp" || strExtension == ".jpg" || strExtension == ".jpeg" || strExtension == ".png") && fileType.StartsWith("image"))
                    {
                        System.Drawing.Image dimg = System.Drawing.Image.FromFile(strNewFilePathAndName);
                        bool marksuc = AddImageSignPic(dimg, strNewFilePathAndName_Mark, strWaterMarkPath, 9, 100, 10);
                        dimg.Dispose();
                        if (marksuc)//加水印成功
                        {
                            if (File.Exists(strNewFilePathAndName))
                            {
                                File.Delete(strNewFilePathAndName);
                            }
                            strNewFileName = strNewFileName_Mark;
                        }
                    }
                    #endregion
                }

                #endregion

                if (!IsUsedFtp)
                {
                    //没有操作
                }
                else
                {
                    #region __________FTP上传__________

                    //将上传到当前服务器的文件 FTP到 另一服务器

                    ART.Common.JFtp ftp = new JFtp();

                    bool ftpsuc = ftp.UploadFtpFile(ConfigurationSettings.AppSettings["FtpServer"], filepath + strNewFileName, ConfigurationSettings.AppSettings["FtpUserName"], ConfigurationSettings.AppSettings["FtpUserPwd"], strAbsolutePath + strNewFileName);
                    if (ftpsuc)
                    {
                        if (File.Exists(strAbsolutePath + strNewFileName))
                        {
                            File.Delete(strAbsolutePath + strNewFileName);
                        }
                    }


                    #endregion
                }



            }
            //返回文件全路径
            return filepath + strNewFileName;

        }

        public string SaveFile(HttpPostedFile file, string filepath)
        {

            string strOldFilePath = file.FileName; //待上传的文件路径

            string strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf(".")).ToLower();//待上传文件的扩展名

            string strNewFileName = GetUniqueString() + strExtension;//按当前时间生成新的文件名

            if (!_ischangename) //如果不改名
            {
                strNewFileName = strOldFilePath.Substring(strOldFilePath.LastIndexOf("\\") + 1).ToLower();
            }


            string fileType = file.ContentType;//待上传文件类型



            filepath = filepath + GetFoderString() + "/";//按当前日期生成新的文件上传路径

            //如果待上传文件的文件名不为空
            if (strOldFilePath != string.Empty)
            {
                if (!isPic(null, file))
                {
                    return "3";
                }
                //验证文件格式
                if (!IsAllowedExtension(strOldFilePath))
                {
                    return "0";
                }
                //验证文件大小
                if (!IsAllowedLength(file.ContentLength))
                {
                    return "1";
                }


                //加水印后的图片的文件名
                string strNewFileName_Mark = GetUniqueString() + "_Mark" + strExtension;

                //水印图片绝对路径
                string strWaterMarkPath = System.Web.HttpContext.Current.Server.MapPath(_strwatermarkpath);

                string strNewFilePathAndName_Mark = "";
                string strAbsolutePath = string.Empty;//要上传文件的绝对路径
                if (!IsUsedFtp)
                {
                    strAbsolutePath = System.Web.HttpContext.Current.Server.MapPath(filepath);

                }
                else //如果启用FTP，则先上传到本地的temp文件夹下
                {
                    strAbsolutePath = System.Web.HttpContext.Current.Server.MapPath("/temp/");
                }
                #region __________本地上传__________




                string strNewFilePathAndName = strAbsolutePath + strNewFileName; //文件上传后的路径+文件名


                strNewFilePathAndName_Mark = strAbsolutePath + strNewFileName_Mark;//加水印图片后的路径+文件名

                //如果文件夹不存在 则创建

                if (!Directory.Exists(strAbsolutePath))
                {
                    Directory.CreateDirectory(strAbsolutePath);
                }

                //上传
                file.SaveAs(strNewFilePathAndName);

                //添加水印
                if (_iswatermark == true)
                {
                    #region ___水印___
                    if ((strExtension == ".bmp" || strExtension == ".jpg" || strExtension == ".jpeg" || strExtension == ".png") && fileType.StartsWith("image"))
                    {
                        System.Drawing.Image dimg = System.Drawing.Image.FromFile(strNewFilePathAndName);
                        bool marksuc = AddImageSignPic(dimg, strNewFilePathAndName_Mark, strWaterMarkPath, 9, 100, 10);
                        dimg.Dispose();
                        if (marksuc)//加水印成功
                        {
                            if (File.Exists(strNewFilePathAndName))
                            {
                                File.Delete(strNewFilePathAndName);
                            }
                            strNewFileName = strNewFileName_Mark;
                        }
                    }
                    #endregion
                }

                #endregion

                if (!IsUsedFtp)
                {
                    //没有操作
                }
                else
                {
                    #region __________FTP上传__________

                    //将上传到当前服务器的文件 FTP到 另一服务器

                    ART.Common.JFtp ftp = new JFtp();

                    bool ftpsuc = ftp.UploadFtpFile(ConfigurationSettings.AppSettings["FtpServer"], filepath + strNewFileName, ConfigurationSettings.AppSettings["FtpUserName"], ConfigurationSettings.AppSettings["FtpUserPwd"], strAbsolutePath + strNewFileName);
                    if (ftpsuc)
                    {
                        if (File.Exists(strAbsolutePath + strNewFileName))
                        {
                            File.Delete(strAbsolutePath + strNewFileName);
                        }
                    }


                    #endregion
                }

            }
            //返回文件全路径
            return filepath + strNewFileName;

        }

        /// <summary>
        /// 加图片水印
        /// </summary>
        /// <param name="filename">加水印后的图片的绝对路径+文件名</param>
        /// <param name="watermarkFilename">水印文件名</param>
        /// <param name="watermarkStatus">图片水印位置1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">图片质量0-100</param>
        /// <param name="watermarkTransparency">图片水印透明度 取值范围1--10 (10为不透明)</param>
        public bool AddImageSignPic(System.Drawing.Image img, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            Graphics g = Graphics.FromImage(img);
            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            System.Drawing.Image watermark = new Bitmap(watermarkFilename);
            System.Drawing.Imaging.ImageAttributes imageAttributes = new System.Drawing.Imaging.ImageAttributes();
            try
            {

                if (watermark.Height >= img.Height || watermark.Width >= img.Width)
                {
                    return false;
                }
                ColorMap colorMap = new ColorMap();

                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                ColorMap[] remapTable = { colorMap };

                imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                float transparency = 0.5F;
                if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
                {
                    transparency = (watermarkTransparency / 10.0F);
                }

                float[][] colorMatrixElements = {
												new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
												new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
												new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
												new float[] {0.0f,  0.0f,  0.0f,  transparency, 0.0f},
												new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
											};

                ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

                imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

                int xpos = 0;
                int ypos = 0;

                switch (watermarkStatus)
                {
                    #region ______水印位置__________
                    case 1:
                        xpos = (int)(img.Width * (float).01);
                        ypos = (int)(img.Height * (float).01);
                        break;
                    case 2:
                        xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                        ypos = (int)(img.Height * (float).01);
                        break;
                    case 3:
                        xpos = (int)((img.Width * (float).99) - (watermark.Width));
                        ypos = (int)(img.Height * (float).01);
                        break;
                    case 4:
                        xpos = (int)(img.Width * (float).01);
                        ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                        break;
                    case 5:
                        xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                        ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                        break;
                    case 6:
                        xpos = (int)((img.Width * (float).99) - (watermark.Width));
                        ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                        break;
                    case 7:
                        xpos = (int)(img.Width * (float).01);
                        ypos = (int)((img.Height * (float).99) - watermark.Height);
                        break;
                    case 8:
                        xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                        ypos = (int)((img.Height * (float).99) - watermark.Height);
                        break;
                    case 9:
                        xpos = (int)((img.Width * (float).99) - (watermark.Width));
                        ypos = (int)((img.Height * (float).99) - watermark.Height);
                        break;
                    #endregion
                }

                g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);
                //g.DrawImage(watermark, new System.Drawing.Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, System.Drawing.GraphicsUnit.Pixel);

                ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo ici = null;
                foreach (ImageCodecInfo codec in codecs)
                {
                    if (codec.MimeType.IndexOf("jpeg") > -1)
                    {
                        ici = codec;
                    }
                }
                EncoderParameters encoderParams = new EncoderParameters();
                long[] qualityParam = new long[1];
                if (quality < 0 || quality > 100)
                {
                    quality = 80;
                }
                qualityParam[0] = quality;

                EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
                encoderParams.Param[0] = encoderParam;

                if (ici != null)
                {
                    img.Save(filename, ici, encoderParams);
                }
                else
                {
                    img.Save(filename);
                }
                return true;

            }
            finally
            {
                g.Dispose();
                img.Dispose();
                watermark.Dispose();
                imageAttributes.Dispose();
            }
        }


        /// <summary>
        /// 裁剪图片  可加水印
        /// </summary>
        /// <param name="sourceUrl">要加载的图像文件(本地格式：/xxx/xx.jpg)</param>
        /// <param name="cutoutUrl">裁剪后文件保存路径/web/upload/</param>
        /// <param name="x">起点的横坐标</param>
        /// <param name="y">起点的竖坐标</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns>返回上传后文件全路径</returns>
        public string CutOutImage(string sourceUrl, string outUrlPath, int x, int y, int width, int height)
        {

            outUrlPath = outUrlPath + GetFoderString() + "/";//带上传文件路径+日期
            string obsoluteOutUrl = System.Web.HttpContext.Current.Server.MapPath(outUrlPath); //输出图片绝对路径
            string obsoluteSourceUrl = System.Web.HttpContext.Current.Server.MapPath(sourceUrl);//原图绝对路径
            string strExtension = sourceUrl.Substring(sourceUrl.LastIndexOf(".")).ToLower();//待上传文件的扩展名

            string sourceFileName = GetUniqueString() + "tmp" + strExtension; ;//待上传文件 上传到本地临时文件的文件名

            string GetFileName = GetUniqueString() + strExtension;//按当前时间生成新的文件名


            System.Drawing.Image tmpImg = System.Drawing.Image.FromFile(obsoluteSourceUrl);
            Bitmap tmpBitmap = new Bitmap(tmpImg);
            try
            {
                Rectangle cloneRect = new Rectangle(x, y, width, height);
                PixelFormat format = tmpBitmap.PixelFormat;
                Bitmap cloneBitmap = tmpBitmap.Clone(cloneRect, format);

                //加水印后的图片的文件名
                string strNewFileName_Mark = GetUniqueString() + "_Mark" + strExtension;

                //水印图片绝对路径
                string strWaterMarkPath = System.Web.HttpContext.Current.Server.MapPath(_strwatermarkpath);

                string strNewFilePathAndName_Mark = "";//加水印图片后的路径+文件名


                #region __________保存在本地__________

                //如果文件夹不存在 则创建
                if (!Directory.Exists(obsoluteOutUrl))
                {
                    Directory.CreateDirectory(obsoluteOutUrl);
                }

                cloneBitmap.Save(obsoluteOutUrl + GetFileName);
                // 释放资源
                tmpImg.Dispose();
                tmpImg = (System.Drawing.Image)cloneBitmap.Clone();
                tmpBitmap.Dispose();


                //添加水印
                if (_iswatermark == true)
                {
                    if ((strExtension == ".bmp" || strExtension == ".jpg" || strExtension == ".jpeg" || strExtension == ".png"))
                    {
                        strNewFilePathAndName_Mark = obsoluteOutUrl + strNewFileName_Mark;//加水印图片后的路径+文件名
                        AddImageSignPic(System.Drawing.Image.FromFile(obsoluteOutUrl + GetFileName), strNewFilePathAndName_Mark, strWaterMarkPath, 9, 100, 10);
                        if (File.Exists(obsoluteOutUrl + GetFileName))
                        {
                            File.Delete(obsoluteOutUrl + GetFileName);
                        }
                        GetFileName = strNewFileName_Mark;
                    }
                }

                //删除原图片
                if (File.Exists(obsoluteSourceUrl))
                {
                    File.Delete(obsoluteSourceUrl);
                }

                #endregion


                return outUrlPath + GetFileName;


            }
            catch (Exception ex)
            {
                tmpBitmap.Dispose();
                throw ex;
            }
        }

        ///<summary>
        ///判断上传文件格式 
        ///</summary>
        ///<paramname = "hifile">FileUpload控件</param>
        ///<returns>允许则返回true,否则返回false</returns>
        private bool IsAllowedExtension(string strOldFilePath)
        {
            string strExtension = "all";
            //允许上传的扩展名可选image,all
            if (_filetype.ToLower() == "all")
            {
                return true;
            }
            if (_filetype.ToLower() == "fj")
            {
                strExtension = ".doc,.docx,.xls,.txt,.xlsx,.gif,.jpg,.jpeg,.png,.rar,.swf,.midi,.mp3,.wav,.avi,.pdf";
            }
            if (_filetype.ToLower() == "office")
            {
                strExtension = ".doc,.xls,.txt,.xlsx";
            }
            if (_filetype.ToLower() == "image")
            {
                strExtension = ".gif,.jpg,.jpeg,.png";
            }
            if (_filetype.ToLower() == "flash")
            {
                strExtension = ".swf";
            }
            if (_filetype.ToLower() == "media")
            {
                strExtension = ".midi,.mp3,.wav,.avi";
            }
            if (_filetype.ToLower() == "xml")
            {
                strExtension = ".xml";
            }
            if (_filetype.ToLower() == "pdf")
            {
                strExtension = ".pdf";
            }
            //Midi、Wav、AIFF、AU、MP3
            string[] arrExtension = strExtension.Split(',');
            if (strOldFilePath != string.Empty)
            {
                //取得上传文件的扩展名
                strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf(".")).ToLower();
                //判断该扩展名是否合法
                for (int i = 0; i < arrExtension.Length; i++)
                {
                    if (strExtension.Equals(arrExtension[i]))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 判断上传文件大小是否超过最大值
        /// </summary>
        /// <param name="hifile">FileUpload控件</param>
        /// <returns>超过最大值返回false,否则返回true.</returns>
        private bool IsAllowedLength(int length)
        {

            //如果上传文件的大小超过最大值,返回flase,否则返回true.
            if (length > _filesize * 1024)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 获取一个不重复的文件名
        /// </summary>
        /// <returns></returns>
        private string GetUniqueString()
        {
            return DateTime.Now.ToString("HHmmssfff");
        }

        /// <summary>
        /// 获取文件夹名 0908
        /// </summary>
        /// <returns></returns>
        private string GetFoderString()
        {
            return DateTime.Now.Year.ToString().Substring(2) + DateTime.Now.ToString("MM");
        }
        /// <summary>
        /// 判断上传是否是图片
        /// </summary>
        /// <param name="file"></param>
        /// <param name="fufile"></param>
        /// <returns></returns>
        private bool isPic(FileUpload file, HttpPostedFile fufile)
        {
            if (_filetype.ToLower() != "image")
            {
                return true;
            }
            bool flag = false;
            string path = "";
            try
            {

                if (file != null)
                {
                    path = Utils.GetMapPath("~/UpLoads/tmp/") + GetUniqueString() + Path.GetExtension(file.FileName);
                    Utils.CreateDir(Path.GetDirectoryName(path));
                    file.SaveAs(path);
                }
                if (fufile != null)
                {
                    path = Utils.GetMapPath("~/UpLoads/tmp/") + GetUniqueString() + Path.GetExtension(fufile.FileName);
                    Utils.CreateDir(Path.GetDirectoryName(path));
                    fufile.SaveAs(path);
                }
                //RwLog.Log(path);
                if (File.Exists(path))
                {
                    System.Drawing.Image image = System.Drawing.Image.FromFile(path);
                    try
                    {
                        Size size = image.Size;
                        flag = true;
                    }
                    catch //(System.Exception ex)
                    {

                    }
                    finally
                    {
                        image.Dispose();
                    }

                }

            }
            catch //(System.Exception ex)
            {

            }
            if (path != "")
            {
                File.Delete(path);
            }
            return flag;
        }





        #region __________裁剪头像__________


        //如缩放图片 则先创建缩略图  返回文件路径+文件名
        public string SaveCutPic(string pPath, string pSavedPath, int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY, int imageWidth, int imageHeight)
        {
            using (System.Drawing.Image originalImg = System.Drawing.Image.FromFile(pPath))
            {
                if (originalImg.Width == imageWidth && originalImg.Height == imageHeight)
                {
                    originalImg.Dispose();
                    return SaveCutPic(pPath, pSavedPath, pPartStartPointX, pPartStartPointY, pPartWidth, pPartHeight,
                            pOrigStartPointX, pOrigStartPointY);

                }
                //取得上传文件的扩展名
                string strExtension = pPath.Substring(pPath.LastIndexOf(".")).ToLower();

                string filename = GetUniqueString() + strExtension;
                string filePath = pSavedPath + "\\" + GetFoderString() + "\\" + filename;

                Bitmap thumimg = MakeThumbnail(originalImg, imageWidth, imageHeight);

                Bitmap partImg = new Bitmap(pPartWidth, pPartHeight);

                Graphics graphics = Graphics.FromImage(partImg);
                Rectangle destRect = new Rectangle(new Point(pPartStartPointX, pPartStartPointY), new Size(pPartWidth, pPartHeight));//目标位置
                Rectangle origRect = new Rectangle(new Point(pOrigStartPointX, pOrigStartPointY), new Size(pPartWidth, pPartHeight));//原图位置（默认从原图中截取的图片大小等于目标图片的大小）

                //文字水印  
                Graphics G = Graphics.FromImage(partImg);
                //Font f = new Font("Lucida Grande", 6);
                //Brush b = new SolidBrush(Color.Gray);
                G.Clear(Color.White);
                // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。 
                G.InterpolationMode = InterpolationMode.HighQualityBicubic;
                // 指定高质量、低速度呈现。 
                G.SmoothingMode = SmoothingMode.HighQuality;

                graphics.DrawImage(thumimg, destRect, origRect, GraphicsUnit.Pixel);
                //G.DrawString("Xuanye", f, b, 0, 0);
                G.Dispose();

                originalImg.Dispose();

                if (File.Exists(filePath))
                {
                    File.SetAttributes(filePath, FileAttributes.Normal);
                    File.Delete(filePath);
                }
                partImg.Save(filePath, ImageFormat.Jpeg);

                partImg.Dispose();
                thumimg.Dispose();

                //删除源文件
                if (File.Exists(pPath))
                {
                    File.Delete(pPath);
                }



                return GetFoderString() + "/" + filename;
            }
        }

        // 则先创建缩略图
        public Bitmap MakeThumbnail(System.Drawing.Image fromImg, int width, int height)
        {
            Bitmap bmp = new Bitmap(width, height);
            int ow = fromImg.Width;
            int oh = fromImg.Height;

            //新建一个画板
            Graphics g = Graphics.FromImage(bmp);

            //设置高质量插值法
            g.InterpolationMode = InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            g.DrawImage(fromImg, new Rectangle(0, 0, width, height),
                new Rectangle(0, 0, ow, oh),
                GraphicsUnit.Pixel);

            return bmp;

        }

        //未缩放图片
        public string SaveCutPic(string pPath, string pSavedPath, int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY)
        {
            //取得上传文件的扩展名
            string strExtension = pPath.Substring(pPath.LastIndexOf(".")).ToLower();
            string filename = GetUniqueString() + strExtension;
            string filePath = pSavedPath + GetFoderString() + "\\" + filename;

            using (System.Drawing.Image originalImg = System.Drawing.Image.FromFile(pPath))
            {
                Bitmap partImg = new Bitmap(pPartWidth, pPartHeight);
                Graphics graphics = Graphics.FromImage(partImg);
                Rectangle destRect = new Rectangle(new Point(pPartStartPointX, pPartStartPointY), new Size(pPartWidth, pPartHeight));//目标位置
                Rectangle origRect = new Rectangle(new Point(pOrigStartPointX, pOrigStartPointY), new Size(pPartWidth, pPartHeight));//原图位置（默认从原图中截取的图片大小等于目标图片的大小）

                //注释 文字水印  
                Graphics G = Graphics.FromImage(partImg);
                //Font f = new Font("Lucida Grande", 6);
                //Brush b = new SolidBrush(Color.Gray);
                G.Clear(Color.White);
                // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。 
                G.InterpolationMode = InterpolationMode.HighQualityBicubic;
                // 指定高质量、低速度呈现。 
                G.SmoothingMode = SmoothingMode.HighQuality;

                graphics.DrawImage(originalImg, destRect, origRect, GraphicsUnit.Pixel);
                //G.DrawString("Xuanye", f, b, 0, 0);
                G.Dispose();

                originalImg.Dispose();

                if (File.Exists(filePath))
                {
                    File.SetAttributes(filePath, FileAttributes.Normal);
                    File.Delete(filePath);
                }
                partImg.Save(filePath, ImageFormat.Jpeg);
                partImg.Dispose();
                graphics.Dispose();

            }
            //删除源文件
            if (File.Exists(pPath))
            {
                File.Delete(pPath);
            }

            return GetFoderString() + "/" + filename;
        }

        #endregion


    }


}
